package com.example.demo.controller;


import com.example.demo.model.Klass;
import com.example.demo.service.KlassService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.UUID;

@Controller
@RequestMapping("klass")
public class KlassController {
    @Autowired
    private KlassService klassService;
    @RequestMapping("list")
    public String list(ModelMap map, Klass klass){
        if ("".equals(klass.getName()))
        {
            klass.setName(null);
        }
        if("".equalsIgnoreCase(klass.getMajor())){
            klass.setMajor(null);
        }
        map.put("klasslist",klassService.findAll());
        return "klass/list";
    }
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id){
        System.out.println(id);
        klassService.deleteById(id);
        return "redirect:/klass/list";
    }

    @RequestMapping("create")
    public String create(){
        return"klass/create";
    }

    @RequestMapping("save")
    public String save(Klass k) {
        if(k.getId() == null){
            k.setId(UUID.randomUUID().toString());
            klassService.save(k);
        }
        else{
            klassService.update(k);
        }
        return "redirect:/klass/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id,ModelMap map) {
        Klass k =klassService.getReferenceById(id);
        map.put("klass",k);
        return "klass/update";
    }
}
